package com.goldsprite.projecttemplategenerator.testold;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpFileDownloader {

	public static void main(String[] args) {
		// 替换为你的有效下载链接
		String downloadUrl = "https://gitee.com/shikeik/project-template-generator/repository/blazearchive/master.zip?Expires=1736067875&Signature=kC032GIPLpF4ywS3lNn63rWM3EuZsej1z7QmixI29qE%3D";
		String outputFileName = "resources/project-template.zip"; // 保存文件名

		try {
			downloadFile(downloadUrl, outputFileName);
			System.out.println("下载完成: " + outputFileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static File downloadFile(String urlStr, String outputFilePath) throws IOException {
		return downloadFile(urlStr, outputFilePath, 0, null);
	}
	public static File downloadFile(String urlStr, String outputFilePath, int interval, ProgressCallback callback) throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");

		// 模拟浏览器 User-Agent，避免一些站点拒绝爬虫
		connection.setRequestProperty("User-Agent", "Mozilla/5.0");

		// 检查 HTTP 响应码
		int responseCode = connection.getResponseCode();
		if (responseCode != HttpURLConnection.HTTP_OK) {
			throw new IOException("无法下载文件，HTTP 响应码: " + responseCode);
		}

		// 获取文件总大小（如果服务器支持）
		long totalSize = connection.getContentLengthLong();
		if (totalSize == -1) {
			System.out.println("文件大小未知（服务器未返回 Content-Length）");
		} else {
			System.out.println("文件总大小: " + (totalSize / 1024) + " KB");
		}

		File outputFile = new File(outputFilePath);
		File parentDir = outputFile.getParentFile();
		if (parentDir != null && !parentDir.exists()) {
			boolean created = parentDir.mkdirs(); // 创建目录
			if (!created) {
				throw new IOException("Failed to create directory: " + parentDir);
			}
		}

		// 创建输入流和输出流
		try (InputStream inputStream = connection.getInputStream();
			 FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath)) {

			byte[] buffer = new byte[4096];
			int bytesRead;
			long downloadedBytes = 0;
			long lastReportedKb = 0;

			System.out.println("正在下载文件...");
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				fileOutputStream.write(buffer, 0, bytesRead);
				downloadedBytes += bytesRead;

				// 每个 interval 调用回调
				if(callback != null) {
					long downloadedKb = downloadedBytes / 1024;
					if (downloadedKb - lastReportedKb >= interval) {
						lastReportedKb = downloadedKb;
						callback.onProgress(downloadedKb, totalSize / 1024);
					}
				}
			}
		}

		System.out.println("文件下载成功: " + outputFilePath);

		return outputFile;
	}
	

	public interface ProgressCallback {
		void onProgress(long downloadedKb, long totalKb);
	}
}
